package com.jiyang.jyandroid.test04;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jiyang.jyandroid.BaseActivity;
import com.jiyang.jyandroid.CommUtil;
import com.jiyang.jyandroid.R;
import com.jiyang.jyandroid.bean.DBOpenHelper;
import com.jiyang.jyandroid.bean.Daily;
import com.jiyang.jyandroid.bean.SpUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jy on 2016/11/18.
 * 文件操作
 */

public class Four_1and3Activity extends BaseActivity {
    private EditText etTitle, etContent;
    private AlertDialog alertDialog;
    private MyAdapter myAdapter;
    private List<Daily> dailies;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_file);
        initView();
    }

    private void initView() {
        etTitle = (EditText) findViewById(R.id.et_title);
        etContent = (EditText) findViewById(R.id.et_content);
        TextView tvDate = (TextView) findViewById(R.id.tv_data_show);
        Button btnOpen = (Button) findViewById(R.id.btn_open_dialy);
        RadioGroup radioGroupSve = (RadioGroup) findViewById(R.id.radio_group);
        ListView listView = (ListView) LayoutInflater.from(this).inflate(R.layout.layout_daily_dialog, null);
        alertDialog = new AlertDialog.Builder(this)
                .setPositiveButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setTitle("日记详情")
                .setView(listView)
                .create();
        //
        btnOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                readDaily();
            }
        });
        radioGroupSve.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.radio_save_sp:
                        saveToSp();
                        break;
                    case R.id.radio_save_file:
                        saveToFile();
                        break;
                    case R.id.radio_save_sqLite:
                        saveToDb();
                        break;
                }
            }
        });
        //
        tvDate.setText(CommUtil.GetDateStr());
        dailies = new ArrayList<>();
        myAdapter = new MyAdapter();
        listView.setAdapter(myAdapter);
    }

    /**
     * 从sp和sqLite中读取
     */
    private void readDaily() {
        dailies.clear();
        //从SP读取
        Daily daily = new SpUtil(Four_1and3Activity.this).getDaily();
        if (!daily.content.equals("")) {
            dailies.add(daily);
        }
        //从数据库读取
        SQLiteDatabase sqLiteDatabase = DBOpenHelper.getInstance(this).getReadableDatabase();
        Cursor cursor = sqLiteDatabase.query(DBOpenHelper.TABLE_DAILY, null, null, null, null, null, null);
        sqLiteDatabase.beginTransaction();
        //纪录指针移动到第一行
        if (cursor.moveToFirst()) {
            do {
                String title, content, time;
                title = cursor.getString(cursor.getColumnIndex("title"));
                content = cursor.getString(cursor.getColumnIndex("content"));
                time = cursor.getString(cursor.getColumnIndex("time"));
                dailies.add(new Daily(title, content, time));
            } while (cursor.moveToNext());
        }
        cursor.close();
        sqLiteDatabase.endTransaction();
        //数据显示到对话框
        myAdapter.notifyDataSetChanged();
        alertDialog.show();
    }

    /**
     * 保存到SharePreference
     */
    private void saveToSp() {
        Daily daily = new Daily(etTitle.getText().toString(),
                etContent.getText().toString(),
                CommUtil.GetDateStr());
        SpUtil spUtil = new SpUtil(this);
        spUtil.saveDaily(daily);
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    private void saveToFile() {
        Toast.makeText(this, "无SD卡", Toast.LENGTH_SHORT).show();
    }

    /**
     * 保存到数据库
     */
    private void saveToDb() {
        SQLiteDatabase sqLiteDatabase = DBOpenHelper.getInstance(this).getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("title", etTitle.getText().toString());
        contentValues.put("content", etContent.getText().toString());
        contentValues.put("time", CommUtil.GetDateStr());
        sqLiteDatabase.insert(DBOpenHelper.TABLE_DAILY, null, contentValues);
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return dailies.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            if (view == null) {
                viewHolder = new ViewHolder();
                view = LayoutInflater.from(Four_1and3Activity.this).inflate(R.layout.item_daily, null);
                viewHolder.tvTitle = (TextView) view.findViewById(R.id.tv_daily_title);
                viewHolder.tvContent = (TextView) view.findViewById(R.id.tv_daily_content);
                viewHolder.tvDate = (TextView) view.findViewById(R.id.tv_daily_date);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.tvTitle.setText(dailies.get(i).title);
            viewHolder.tvContent.setText(dailies.get(i).content);
            viewHolder.tvDate.setText(dailies.get(i).date);
            return view;
        }

        class ViewHolder {
            TextView tvTitle;
            TextView tvContent;
            TextView tvDate;
        }
    }
}
